<script>
import chatWindow from "../../components/chat-window.vue";
import { getLocal } from "../../utils/utils";
export default {
  components: {
    chatWindow,
  },
};
</script>

<script setup>
import NIM from "@yxim/nim-web-sdk/dist/SDK/NIM_Web_NIM";
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, onMounted } from "vue";
import { mainStore } from '../../store/main'

const messageStore = mainStore()
const router = useRouter();
const route = useRoute();
const title = ref("");
title.value = route.meta.title;
const chatWindowSon = ref(null)
// 获取云信数据
let nimInfo = JSON.parse(getLocal("yv_token"))
console.log(messageStore,'mainStore.message')

// 聊天相关数据
messageStore.message.account = nimInfo.accid
messageStore.message.token = nimInfo.token
messageStore.message.name = nimInfo.name

let message = reactive({
  chatRecord: {}, // 聊天记录
  chatFriends: null,
  account: messageStore.message.account, // 账号
  token: messageStore.message.token, // token
  name: messageStore.message.name // 名字
});

// 聊天窗口
const chatShow = ref(false); // 聊天窗口
const formUser = ref("");  // 当前聊天对象
const addUser = ref("");  // 要添加的好友


const onDisconnectError = ref();
// 初始化
const initNIM = () => {
  // 获取token,
  messageStore.NIMoption = NIM.getInstance({
    debug: false,
    appKey: "5f87913b2c71f0bd6df15ea724143ea0",
    account: messageStore.message.account,
    token: messageStore.message.token,
    db: false, // 不使用数据库
    onconnect: onConnect,
    onwillreconnect: onWillReconnect,
    ondisconnect: onDisconnect,
    onerror: onError,
    onmsg: onMsg,
    onupdatesession: onUpdateSession,
    // 好友关系
    onfriends: onFriends,
  });
  console.log(messageStore.NIMoption,'初始化init');
};

// 连接建立后的回调
let onConnect = (optional) => {
  console.log(optional, "onConnect");
  getFriendsList()
};
// 即将重连的回调
let onWillReconnect = (optional) => {
  console.log(optional, "onWillReconnect");
};
// 断开连接后的回调
let onDisconnect = (error) => {
  console.log(error, "onDisconnect");
  if (error) {
    switch (error.code) {
      // 账号或者密码错误, 请跳转到登录页面并提示错误
      case 302:
        onDisconnectError.value = "账号或者密码错误, 请刷新后重试";
        break;
      // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
      case 417:
        onDisconnectError.value = "重复登录, 已经在其它端登录了";
        break;
      // 被踢, 请提示错误后跳转到登录页面
      case "kicked":
        onDisconnectError.value = "您已经被踢出，请重新登录";
        break;
      default:
        onDisconnectError.value = "您已断开连接，请刷新页面重新发起会话！";
        break;
    }
  }
};
// 错误时候的回调
let onError = (optional) => {
  console.log(optional, "onError");
};
// 收到消息后的回调
let onMsg = (optional) => {
  console.log(optional, "onMsg");
};
// 会话更新后的回调
let onUpdateSession = (optional) => {
  // 判断数据是否增加成功
  if (optional.lastMsg.status == "success") {
    // 添加更新后的数据
    messageStore.message.chatRecord[formUser.value].push(optional.lastMsg)
  }
};

// 获取好友列表的的回调
let onFriends = (friends) => {
  messageStore.message.chatFriends = messageStore.NIMoption.mergeFriends(messageStore.message.chatFriends, friends);
  messageStore.message.chatFriends = messageStore.NIMoption.cutFriends(messageStore.message.chatFriends, friends.invalid);
  console.log('收到好友列表', messageStore.message.chatFriends.value,friends);
  refreshFriendsUI();

};

// 添加好友列表的的回调
let onAddFriend = (friends) => {
  messageStore.message.chatFriends = messageStore.NIMoption.mergeFriends(data.friends, friend);
  refreshFriendsUI();
}

// ---------------------------------------------------------------------------------

// 获取聊天记录
let getHistoryMsgs = (formUser) => {
  let getHistoryMsgsDone = (error, obj) => {
    // console.log('获取云端历史记录' + (!error?'成功':'失败'), error, obj);
    if (!error) {
      messageStore.message.chatRecord[formUser] = obj.msgs.reverse();
      console.log(messageStore.message.chatRecord, "获取到的聊天记录");
    }
  };

  messageStore.NIMoption.getHistoryMsgs({
    scene: "p2p",
    to: formUser,
    limit: 20,
    done: getHistoryMsgsDone,
  });
};

// 发送信息
const sendText = (sendText) => {
  const sendMsgDone = (error, msg) => {
    console.log(
      "发送" +
      msg.scene +
      " " +
      msg.type +
      "消息" +
      (!error ? "成功" : "失败") +
      ", id=" +
      msg.idClient,
      error,
      msg
    );
  };
  messageStore.NIMoption.sendText({
    scene: "p2p",
    to: formUser.value,
    text: sendText,
    done: sendMsgDone,
  });
};

// 发起好友列表更新
const getFriendsList = () => {
  function getFriendsDone(error, friends) {
    console.log('获取好友列表' + (!error ? '成功' : '失败'), error, friends);
    if (!error) {
      onFriends(friends);
    }
  }
  // 获取好友列表
  messageStore.NIMoption.getFriends({
    done: getFriendsDone
  });
}

// 发起聊天
const goChat = (user) => {
  chatShow.value = true;
  // 更改当前聊天的对象
  formUser.value = user;
  getHistoryMsgs(formUser.value);
};

// 添加好友
const goAddFriend = () => {
  function addFriendDone(error, obj) {
    console.log('直接加为好友' + (!error ? '成功' : '失败'), error, obj);
    if (!error) {
      onAddFriend(obj.friend);
    }
  }
  console.log(addUser,'addUser');
  messageStore.NIMoption.addFriend({
    account: addUser.value,
    ps: '我是' + messageStore.message.name,
    done: addFriendDone
  });

}

// 刷新好友界面
const refreshFriendsUI = () =>  {
  console.log(messageStore.message.chatFriends,'message.chatFriends')
  // 创建好友列表
  messageStore.message.chatFriends.forEach(element => {
    getHistoryMsgs(element.account)
  });
}

onMounted(() => {
  initNIM();
});
</script>

<template>
  <div class="message">
    <chat-window :messData="messageStore.message.chatRecord[formUser]" @sendMessage="sendText" @closeChat="chatShow = false" v-if="chatShow" ref="chatWindowSon">
    </chat-window>
    <van-nav-bar :title="title" />
    <div class="add_Frends">
      <input type="text" v-model="addUser">
      <div @click="goAddFriend">添加好友</div>
    </div>
    <ul class="contact">
      <li class="contact_list" v-for="(item, index) in messageStore.message.chatFriends"  @click="goChat(item.account)" :key="index">
        <van-image round width="1.3rem" height="1.3rem" src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" />
        <div>
          <p>{{item.account}}</p>
          <p>{{messageStore.message.chatRecord[item.account][messageStore.message.chatRecord[item.account].length - 1].text || ''}}</p>
        </div>
      </li>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
.message {
  position: relative;
  .add_Frends{
    display: flex;
    justify-content: center;
    margin-bottom: 1rem;
    input {
      width: 4.75rem;
      height: 1.1875rem;
    }
    & > div {
      margin-left: .375rem;
      width: 2.75rem;
      height: 1.1875rem;
      line-height: 1.1875rem;
      text-align: center;
      font-size: .4688rem;
      border-radius: 999px;
      background-color: #fedd2b;
    }
  }
  .contact_list {
    margin-top: 0.25rem;
    padding: 0.25rem;
    display: flex;
    font-size: 0.4375rem;
    background-color: #fff;

    p {
      margin: 0;
      margin-left: 0.375rem;
    }
  }
}
</style>
